package com.zhangye.test.api;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.collections.MapUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhangye.test.model.Admin;
import com.zhangye.test.service.SafeSessionService;
import com.zhangye.test.service.WeChatAsyncService;
import com.zhangye.test.service.WeChatQueryService;
import com.zhangye.test.service.WechatOrderInfoService;
import com.zhangye.test.util.XMLPojoMapConverter;


/**
 * 微信支付入口
 * @author Administrator
 *
 */
@Controller
@RequestMapping("api/weChat")
public class WeChatApi {

	@Autowired
	private SafeSessionService safeSessionService;// 安全登录

	@Autowired
	private WechatOrderInfoService weChatOrderInfoService;//创建订单

	@Autowired
	private WeChatQueryService weChatQueryService;//查询订单

	@Autowired
	private WeChatAsyncService weChatAsyncService;//查询订单
	
	
	/**
	 * 创建订单
	 * 作者： 张叶
	 * 创建时间：2018年8月2日  下午5:48:22
	 */
	@ResponseBody
	@RequestMapping("/orderNew")
	public ApiResult orderNew(HttpServletRequest request,String datas){
		ApiResult result = new ApiResult();
		Map<String, Object> map = new HashMap<String, Object>();
		String reqParam = request.getParameter("datas");  
		Admin m = safeSessionService.getCurrent(request);
		if (m != null) {
			JSONObject jasonObject = JSONObject.fromObject(reqParam);
			try {
				map = weChatOrderInfoService.orderNew(jasonObject,m.getId());
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (DocumentException e) {
				e.printStackTrace();
			}
			if (MapUtils.isNotEmpty(map)) {
				if (map.get("status").equals("0")) {
					result.msg.desc = "成功";
					result.msg.status = 0;
					result.data.put("orderInfo", map.get("data"));
					result.data.put("outTradeNo", map.get("outTradeNo"));
				} else if (map.get("status").equals("2")) {
					result.msg.desc = "金额错误，请重试";
					result.msg.status = 3;
				}
			} else {
				result.msg.desc = "系统错误，请重试";
				result.msg.status = 1;
			}
		} else {
			result.msg.desc = "当前登录已失效，请重新登录 ";
			result.msg.status = 2;
		}
		return result;
	}
	
	/**
	 * 查询订单
	 * 作者： 张叶
	 * 创建时间：2018年8月2日  下午5:48:16
	 */
	@ResponseBody
	@RequestMapping("/queryNew")
	public ApiResult queryNew(HttpServletRequest request,String datas){
		ApiResult result = new ApiResult();
		Map<String, Object> map = new HashMap<String, Object>();
		String reqParam = request.getParameter("datas");
		JSONObject jasonObject = JSONObject.fromObject(reqParam);
		try {
			map = weChatQueryService.queryNew(jasonObject);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		if (MapUtils.isNotEmpty(map)) {
			if (map.get("status").equals("0")) {
				result.data.put("outTradeNo", map.get("outTradeNo"));
				result.msg.desc = "支付成功";
				result.msg.status = 0;
			} else if (map.get("status").equals("2")) {
				result.msg.desc = "未查询到订单信息";
				result.msg.status = 2;
			} else if (map.get("status").equals("3")) {
				result.msg.desc = "支付失败";
				result.msg.status = 3;
			} else if (map.get("status").equals("4")) {
				result.msg.desc = (String) map.get("desc");
				result.msg.status = 4;
			} else {
				result.msg.desc = "系统错误，请重试";
				result.msg.status = 1;
			}
		} else {
			result.msg.desc = "系统错误，请重试";
			result.msg.status = 1;
		}
		return result;
	}
	
	
	
	@ResponseBody
	@RequestMapping("/async")
	public ApiResult async(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		try{  
			BufferedReader reader = request.getReader();  

			String line = "";  
			StringBuffer inputString = new StringBuffer();  

			try{  
				PrintWriter writer = response.getWriter();  
				while ((line = reader.readLine()) != null) {  
					inputString.append(line);  
				}  
				if(reader!=null){  
					reader.close();  
				}  
				System.out.println("----[微信回调]接收到的报文---"+inputString.toString()); 
				map = XMLPojoMapConverter.xml2map(inputString.toString());
				try {
					
					weChatAsyncService.async(map);
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (DocumentException e) {
					e.printStackTrace();
				}

			}catch(Exception e){  
				e.printStackTrace();  
			}  
		}catch(Exception ex){  
			ex.printStackTrace();  
		} 
		return null;
	}
	
}
